package com.stlm2.dems.service;

import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.UserService;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.user.entity.Account;
import com.stlm2.dems.user.entity.AccountState;
import com.stlm2.dems.util.CoreLogic;
import com.stlm2.util.Convert;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("commissionService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class CommissionService extends BaseServiceImpl<Commission> {

	@Resource
	private CommissionDao commissionDao;
	@Resource
	private UserService userService;
	@Resource
	private GoodsOrderDao goodsOrderDao;
	@Resource
	private ConfigDao configDao;
	@Resource
	private UserDao userDao;
	@Resource
	private AccountDao accountDao;
	@Resource
	private FmsFlowDao fmsFlowDao;
	@Resource
	private CoreLogic coreLogic;

	@Override
	protected BaseDao <Commission> getDao() {
		return commissionDao;
	}

    public List<ModelMap> convent(List<Commission> commissions) {
		List<ModelMap> list=new ArrayList<ModelMap>();
		for(Commission commission:commissions){
			list.add(buiderModel(commission));
		}
		return list;
    }
	private ModelMap buiderModel(Commission commission) {
		ModelMap map=new ModelMap();
		map.put("id",commission.getId());
		map.put("date", Convert.toFullYMDHMS(commission.getCreateTime()));
		map.put("code",commission.getReferCode());
		map.put("money",commission.getMoney());
		return map;
	}

	public List<Commission> getbyCode(String code) {
		return commissionDao.getbyCode(code);
	}

	public List<ModelMap> conventDetail(List<Commission> commissions) {
		List<ModelMap> list=new ArrayList<ModelMap>();
		for(Commission commission:commissions){
			list.add(buiderModelDetail(commission));
		}
		return list;
	}

	private ModelMap buiderModelDetail(Commission commission) {
		User user=userService.getById(commission.getUpperUserId());
		ModelMap map=new ModelMap();
		map.put("id",commission.getId());
		map.put("source",commission.getCommissionSource().toString());
		map.put("name",user.getName());
		map.put("money",commission.getMoney());
		return map;
	}

	public List<ModelMap> conventAll(List<Commission> commissions) {
		List<ModelMap> list=new ArrayList<ModelMap>();
		for(Commission commission:commissions){
			list.add(buiderModelAll(commission));
		}
		return list;
	}

	private ModelMap buiderModelAll(Commission commission) {
		User upperUser=userService.getById(commission.getUpperUserId());
		User lowerUser=userService.getById(commission.getLowerUserId());
		ModelMap map=new ModelMap();
		map.put("id",commission.getId());
		map.put("source",commission.getCommissionSource().toString());
		map.put("upperUser",upperUser.getName());
		map.put("lowerUser",lowerUser.getName());
		map.put("type",commission.getCommissionType().toString());
		map.put("referCode",commission.getReferCode());
		map.put("orderMoney",commission.getOrderMoney());
		map.put("commissionRate",commission.getCommissionRate());
		map.put("money",commission.getMoney());
		map.put("userLevel",upperUser.getUserLevel().toString());
		map.put("createTime",Convert.toFullYMDHMS(commission.getCreateTime()));
		return map;
	}



	public void partnerLevelCommission(){
		//合伙人推广佣金比例
		Config config9 = new Config();
		config9.setConfigName("PARTNER_RATE");
		Config config10 = configDao.selectOneFromRedis(config9);
		if(config10==null){
			System.out.println("redis中获取PARTNER_RATE对象失败，尝试从数据库中获取");
			config10=configDao.getByName("PARTNER_RATE");
			if(config10==null){
				System.out.println("从数据库中获取PARTNER_RATE对象失败");
				return;
			}
		}

		BigDecimal partnerLevelRate=new BigDecimal(config10.getConfigValue());
		if(partnerLevelRate.compareTo(new BigDecimal(1))==1||partnerLevelRate.compareTo(new BigDecimal(0))==-1){
			System.out.println("获取PARTNER_RATE的值有问题");
			return;
		}
		Calendar currCalendar = Calendar.getInstance();
		int currYear = currCalendar.get(Calendar.YEAR);
		int currMonth = currCalendar.get(Calendar.MONTH) + 1;
		Commission param=new Commission();
		param.setMonth(currMonth);
		param.setYear(currYear);
		param.setCommissionSourceValue(CommissionSource.Partner.getIntValue());
        int num=commissionDao.countNum(param);
        if(num>0){
			System.out.println(currMonth+"月份合伙人已经分过合伙人佣金");
			return;
		}
		List<User> userList=userDao.getUserLevel();
        if(userList!=null &&userList.size()>0){
        	String code="Y"+currYear+"M"+currMonth;
			GoodsOrder goodsOrder=new GoodsOrder();
			goodsOrder.setOrderState(OrderState.Finish);
			goodsOrder.setStartFinishTime(DateUtils.truncate(DateUtils.addMonths(new Date(), -1), Calendar.MONTH));
			goodsOrder.setEndFinishTime(DateUtils.truncate(new Date(), Calendar.MONTH));
			Double totalMoney=goodsOrderDao.sumForCommission(goodsOrder);
			BigDecimal partnerMoney=new BigDecimal(totalMoney).multiply(partnerLevelRate);
            BigDecimal perPartnerMoney=partnerMoney.divide(new BigDecimal(userList.size()));
			perPartnerMoney=perPartnerMoney.setScale(2,BigDecimal.ROUND_DOWN);
			for (User user:userList) {
				Account account=accountDao.getByUserId(user.getId());
				if(account!=null && AccountState.Normal.equals(account.getAccountState())){//合伙人用户的资金账户是否存在
					//佣金记录
					Commission commission=new Commission();
					commission.setUpperUserId(user.getId());
					commission.setUserLevel(user.getUserLevel());
					commission.setCommissionRate(partnerLevelRate);
					commission.setCommissionSource(CommissionSource.Partner);
					commission.setCommissionType(CommissionType.Sale);
					commission.setCreateTime(new Date());
					commission.setReferCode(code);
					commission.setOrderMoney(partnerMoney);
					commission.setMoney(perPartnerMoney);
					commission.setYear(currYear);
					commission.setMonth(currMonth);
					coreLogic.addFundsFlow(user.getId(),perPartnerMoney, FlowSource.Commission, FlowType.Add, null, code);
					coreLogic.changeMoneyAccount(user.getId(),perPartnerMoney,FlowSource.Commission,FlowType.Add);
					commissionDao.add(commission);

				}else {
					System.out.println("合伙人id:"+user.getId()+"的资金账户不存在或用户无效");
				}
			}
		}else {
			System.out.println(currMonth+"月份合伙人还没有产生");
			return;
		}

	}
}